package com.atguigu.eduservice.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.*;
import com.atguigu.eduservice.entity.vo.TeacherQuery;
import com.atguigu.eduservice.mapper.TbDcUserMapper;
import com.atguigu.eduservice.service.*;
import com.atguigu.eduservice.utils.ExcelCommon;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-02-24
 */
@Api(description="讲师管理")
@RestController
@RequestMapping("/eduservice/teacher")
@CrossOrigin
public class EduTeacherController {

    //访问地址： http://localhost:8001/eduservice/teacher/findAll
    //把service注入
    @Autowired
    private EduTeacherService teacherService;
    @Autowired
    private  StudentService studentService;
    @Autowired
    private MainStudentService mainStudentService;

    @Autowired
    private TbDcUserService tbDcUserService;
    @Autowired
    private TbDcUserOriginService tbDcUserOriginService;
    @Autowired
    private ItemsService itemsService;






    //1 查询讲师表所有数据
    //rest风格
    @ApiOperation(value = "所有讲师列表")
    @GetMapping("findAll")
    public R findAllTeacher() {
        //调用service的方法实现查询所有的操作
        List<EduTeacher> list = teacherService.list(null);
        return R.ok().data("items",list);
    }

    @ApiOperation(value = "导入公司产品表")
    @PostMapping("import_items_excel")
    public R import_items_excel(MultipartFile file) throws Exception {
        if (StringUtils.isEmpty(file))
        {
            return R.error().data("error","文件未选择");
        }
        Set<String> key1= new HashSet<>();
//        HashMap<String,Object> hashMap = new
        //System.out.println(hashMap);
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        //产品图片	产品编号	中文品名	英文品名	类型名称	系列	小类	出货数量	外销单价	部门	外箱长度	外箱宽度	外销高度
        hashMap.put("产品图片","Photo");
        hashMap.put("产品编号","ItemNo");
        hashMap.put("中文品名","CHNItemName");
        hashMap.put("英文品名","ENGItemName");
        hashMap.put("类型名称","CHNSpecification");
        hashMap.put("系列","xl");
        hashMap.put("小类","SectionCode");
        //hashMap.put("出货数量","ItemNo");
        hashMap.put("外销单价","SalesPrice");
        hashMap.put("采购单价","PurchasePrice");
        //hashMap.put("部门","ItemNo");
//        hashMap.put("外箱长度","ItemNo");
//        hashMap.put("外箱宽度","ItemNo");

        //List<String> userlist=new ArrayList<>();




      List<JSONObject> results = ExcelCommon.getTestData(hashMap,file,"产品信息");
      List<Items> itemsList =new ArrayList<>();
        List<String> itemaddlist=new ArrayList<>();
        for (int i=0;i<results.size();i++) {
            JSONObject json = results.get(i);
            if (!json.containsKey("error")) {
                Items items=JSON.toJavaObject(json, Items.class);
                items.setRecordID(UUID.randomUUID().toString().toUpperCase());
                //items.setPurchasePrice(0.00);

                if (!Strings.isBlank(items.getItemNo())) {
                    QueryWrapper<Items> wrapperVideo = new QueryWrapper<>();

                    wrapperVideo.eq("[ItemNo]", items.getItemNo());
                    Integer count = itemsService.count(wrapperVideo);

                    if (count == 0) {
                        Boolean issave=itemsService.save(items);
                        if (issave)
                            itemaddlist.add("新增产品,itemno:"+items.getItemNo());

                    }

                }
                itemsList.add(items);
            }
        }
        System.out.println(itemsList);
      return R.ok().data("itemaddlist",itemaddlist);
    }

    @ApiOperation(value = "导入用户与客户对照表")
    @PostMapping("import_user_customer_excel")
    public R import_user_customer_excel(MultipartFile file) throws Exception {

        //String filePath ="D:\\intersky\\前程\\工作\\user_customerid.xlsx";
        //System.out.println(filePath);
        if (StringUtils.isEmpty(file))
        {
            return R.error().data("error","文件未选择");
        }
        Set<String> key1= new HashSet<>();
        HashMap<String,Object> hashMap = ExcelCommon.getProxyPojoValue(new TbDcUserOrigin(),key1);
        //System.out.println(hashMap);
        List<String> userlist=new ArrayList<>();




        List<JSONObject> results = ExcelCommon.getTestData(hashMap,file,"sheet1");

        for (int i=0;i<results.size();i++){
            JSONObject json = results.get(i);
            if (!json.containsKey("error")){
                if (!StringUtils.isEmpty(json.get("createdDate")))
                {
                    String datestring=json.get("createdDate").toString();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    datestring=df.format(HSSFDateUtil.getJavaDate(Double.parseDouble(datestring)));
                    json.put("createdDate",datestring);

                }
                System.out.println(json);

                TbDcUserOrigin tbDcUserOrigin = JSON.toJavaObject(json, TbDcUserOrigin.class);

                QueryWrapper<TbDcUserOrigin> wrapperVideo = new QueryWrapper<>();
                wrapperVideo.eq("[user_id]",tbDcUserOrigin.getUserId());
                wrapperVideo.eq("customer_id",tbDcUserOrigin.getCustomerId());
//                System.out.println(wrapperVideo);
//                System.out.println(tbDcUserService.list(wrapperVideo));

                Integer count = tbDcUserOriginService.count(wrapperVideo);

                if (count == 0) {
                    tbDcUserOriginService.save(tbDcUserOrigin);
                    //if (userlist.indexOf(tbDcUserOrigin.getUserId())==-1)
                    userlist.add("userid:" + tbDcUserOrigin.getUserId() + "/customer_id:" + tbDcUserOrigin.getCustomerId());
                }
            }
        }
        return R.ok().data("userlist",userlist);
    }

    @ApiOperation(value = "导入用户表")
    @PostMapping("import_user_excel")
    public R import_user_excel(MultipartFile file) throws Exception {
        String filePath ="D:\\intersky\\前程\\工作\\user.xlsx";
        Set<String> key1= new HashSet<>();
        HashMap<String,Object> hashMap = ExcelCommon.getProxyPojoValue(new TbDcUser(),key1);
        List<String> userlist=new ArrayList<>();




        List<JSONObject> results = ExcelCommon.getTestData(hashMap,file,"sheet1");
        System.out.println(results);

        for (int i=0;i<results.size();i++){
            JSONObject json = results.get(i);
            if (!json.containsKey("error")){
                TbDcUser tbDcUser = JSON.toJavaObject(json, TbDcUser.class);
                QueryWrapper<TbDcUser> wrapperVideo = new QueryWrapper<>();
                wrapperVideo.eq("[user]",tbDcUser.getUser());
//                System.out.println(wrapperVideo);
//                System.out.println(tbDcUserService.list(wrapperVideo));

                Integer count = tbDcUserService.count(wrapperVideo);
                if (count == 0) {
                    tbDcUserService.save(tbDcUser);
                    userlist.add(tbDcUser.getUser());}

            }
        }
        return R.ok().data("userlist",userlist);
    }
    @ApiOperation(value = "所有学生列表")
    @PostMapping("student_save")
    public R student_findAll() {
        //调用service的方法实现查询所有的操作
        List<Tstudent> liststudent = studentService.list(null);
        Integer hj=0;
        String name="";

        for (int i = 0; i < liststudent.size(); i++) {
            QueryWrapper<Tstudent> wrapperVideo = new QueryWrapper<>();
            wrapperVideo.eq("name", liststudent.get(i).getName());

            Integer count = mainStudentService.count(wrapperVideo);
            if (count == 0) {
                mainStudentService.save(liststudent.get(i));
                hj++;
            if (!StringUtils.isEmpty(name))
                name=name+"/"+liststudent.get(i).getName();
            else
                name=liststudent.get(i).getName();
            }
        }
        List<Tstudent> listmainstudent = mainStudentService.get_studentall();
        return R.ok().data("insert_count",hj).data("insert_name",name).data("items",listmainstudent);
    }

    //2 逻辑删除讲师的方法
    @ApiOperation(value = "逻辑删除讲师")
    @DeleteMapping("{id}")
    public R removeTeacher(@ApiParam(name = "id", value = "讲师ID", required = true)
                                     @PathVariable String id) {
        boolean flag = teacherService.removeById(id);
        if(flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    //3 分页查询讲师的方法
    //current 当前页
    //limit 每页记录数
//    @GetMapping("pageTeacher/{current}/{limit}")
//    public R pageListTeacher(@PathVariable long current,
//                             @PathVariable long limit) {
//        //创建page对象
//        Page<EduTeacher> pageTeacher = new Page<>(current,limit);
//
//        try {
//            int i = 10/0;
//        }catch(Exception e) {
//            //执行自定义异常
//            throw new GuliException(20001,"执行了自定义异常处理....");
//        }
//
//
//        //调用方法实现分页
//        //调用方法时候，底层封装，把分页所有数据封装到pageTeacher对象里面
//        teacherService.page(pageTeacher,null);
//
//        long total = pageTeacher.getTotal();//总记录数
//        List<EduTeacher> records = pageTeacher.getRecords(); //数据list集合
//
//        Map<String,Object> map = new HashMap<>(16);
//        map.put("total",total);
//        map.put("rows",records);
////        return R.ok().data(map);
//
//        return R.ok().data("total",total).data("rows",records);
//    }
    @ApiOperation("分页查询讲师（不带条件）")
    @GetMapping("/pageTeacher/{page}/{size}")
    public R pageTeacher(@ApiParam(value = "page",defaultValue = "1") @PathVariable("page") int page,
                                @ApiParam(value = "size",defaultValue = "10")@PathVariable("size") int size){

        //1.创建page对象
        //调用方法时候，底层封装，把分页所有数据封装到pageTeacher对象里面
        IPage<EduTeacher> teacherPage = new Page<>(page, size);
        teacherService.page(teacherPage, null);

        Map<String,Object> map = new HashMap<>(16);

        map.put("total",teacherPage.getTotal());
        map.put("rows",teacherPage.getRecords());

        return R.ok().data(map);
    }

    //4 条件查询带分页的方法
    @PostMapping("pageTeacherCondition/{current}/{limit}")
    public R pageTeacherCondition(@PathVariable long current,@PathVariable long limit,
                                  @RequestBody(required = false)  TeacherQuery teacherQuery) {
        //创建page对象
        Page<EduTeacher> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
       // 多条件组合查询
        // mybatis学过 动态sql
        String name = teacherQuery.getName();
        Integer level = teacherQuery.getLevel();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(name)) {
            //构建条件
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(level)) {
            wrapper.eq("level",level);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("gmt_create",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("gmt_create",end);
        }

        //排序
        wrapper.orderByDesc("gmt_create");

        //调用方法实现条件查询分页
        teacherService.page(pageTeacher,wrapper);

        long total = pageTeacher.getTotal();//总记录数
        List<EduTeacher> records = pageTeacher.getRecords(); //数据list集合
        return R.ok().data("total",total).data("rows",records);
    }

    //添加讲师接口的方法
    @PostMapping("addTeacher")
    public R addTeacher(@RequestBody EduTeacher eduTeacher) {
        boolean save = teacherService.save(eduTeacher);
        if(save) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    //根据讲师id进行查询
    @GetMapping("getTeacher/{id}")
    public R getTeacher(@PathVariable String id) {
        EduTeacher eduTeacher = teacherService.getById(id);
        return R.ok().data("teacher",eduTeacher);
    }

    //讲师修改功能
//    @PostMapping("updateTeacher")
//    public R updateTeacher(@RequestBody EduTeacher eduTeacher) {
//        boolean flag = teacherService.updateById(eduTeacher);
//        if(flag) {
//            return R.ok();
//        } else {
//            return R.error();
//        }
//    }
    @ApiOperation("修改讲师功能")
    @PutMapping("/updateTeacher/{id}")
    public R updateTeacher(@PathVariable String id, @RequestBody EduTeacher teacher){

        EduTeacher result = teacherService.getById(id);
        BeanUtils.copyProperties(teacher,result);
        result.setId(id);
        boolean updateResult = teacherService.updateById(result);

        if(updateResult){
            return R.ok();
        }else {
            return R.error();
        }
    }
}

